<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/9/16
 * Email: <939369942@qq.com>
 */
namespace basic\listens;

use app\common\repositories\star\StarGiftRecordRepository;
use app\common\repositories\star\StarSendRecordRepository;
use app\common\repositories\sys\GiftBackpackRepository;
use basic\interfaces\ListenerInterface;
use Swoole\Timer;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\swoole\Websocket;

class CurrencyExtensionListen implements ListenerInterface
{
    public function handle($event): void
    {
        Timer::tick(1000*1,function () {
            /**@var $make StarSendRecordRepository**/
            $make = app()->make(StarSendRecordRepository::class);
            $periodInfo = $make->getNowPeriodInfo();
            if($periodInfo['status'] != 1 && !Cache::has('star_open_lottery_key')){
                Cache::set('star_open_lottery_key',$periodInfo['openTime'],10);
                $make->open($periodInfo['openTime']);
            }
        });

        Timer::tick(1000*2,function () {
            $list = app()->make(StarGiftRecordRepository::class)->getSearch()->where('send_id',1)->select();
            if(count($list) && !Cache::has('star_open_give_gift')){
                Cache::set('star_open_give_gift',1,30);
                foreach ($list as $i){
                    $db1 = Db::connect('mysql');
                    $db2 = Db::connect('sys');
                    try {
                        $db1->startTrans();
                        $db2->startTrans();

                        # todo 给用户赠送礼物  =>setBackpackGiftNumber
                        /**@var $sysGiftMake  GiftBackpackRepository **/
                        $sysGiftMake = app()->make(GiftBackpackRepository::class);
                        $sysGift = $sysGiftMake->getSearch()
                            ->where(['user_id'=>$i['uid'],'gift_id'=>$i['gift_id']])->find();
                        if($sysGift){
                            $sysGiftMake->incrNumberField($sysGift['id'],'number',$i['count']);
                        }else{
                            $sysGiftMake->create([
                                'user_id' =>$i['uid'],
                                'gift_id' =>$i['gift_id'],
                                'number'  =>$i['count'],
                            ]);
                        }
                        $i->save(['send_id'=>0]);

                        $db1->commit();
                        $db2->commit();

                    }catch (\Exception $exception){
                        $db1->rollback();
                        $db2->rollback();
                        Log::error('【星际赠送礼物失败】:'.$exception->getMessage());
                        throw $exception;
                    }
                }
                Cache::delete('star_open_give_gift');
            }

        });
    }
}